package com.cyan.app.workflow.util.network;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.cyan.app.workflow.util.BaseHelper;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;

/**
 * Created by DXW on 2016/3/2.
 */
public class GetJsonData {

    private static int connectTimeout = 30 * 1000;
    private static int readTimeout = 30 * 1000;
    public static Proxy mProxy = null;
    public static Context mContext;

    public static String getInputStreamByPost(String urlPath, String action, String params, Context context) throws Exception {
        mContext = context;
        urlPath = urlPath + "?";
        String data =String.format("action=%s&params=%s",action,params);// "action=207&params={\"Itnbr\":\"BA10001\"}";
        // 检查网络
        detectProxy();
        // 发送请求
        HttpURLConnection conn = null;
        String strResponse = null;
        try {
            URL url = new URL(urlPath);
            // 打开连接
            if (mProxy != null) {
                conn = (HttpURLConnection) url.openConnection(mProxy);
            } else {
                conn = (HttpURLConnection) url.openConnection();
            }
            // 设置提交方式
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            // post方式不能使用缓存
            conn.setUseCaches(false);
            conn.setInstanceFollowRedirects(true);
            byte[] requestStringBytes = data.getBytes("UTF-8");
            // 设置连接超时时间
            conn.setConnectTimeout(connectTimeout);
            conn.setReadTimeout(readTimeout);
            // 配置本次连接的Content-Type，配置为application/x-www-form-urlencoded
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置浏览器编码
            conn.setRequestProperty("Charset", "UTF-8");
            // 开始连接
            conn.connect();

            OutputStream dos = conn.getOutputStream();
            // 将请求参数数据向服务器端发送
            dos.write(requestStringBytes);
            dos.flush();

            if (conn.getResponseCode() == 200) {
                // 获得服务器端输出流
                InputStream content = conn.getInputStream();
                strResponse = BaseHelper.convertStreamToString(content);
//				System.out.println("response " + strResponse);
                mProxy = null;
                return strResponse;
            }
        } catch (IOException e) {
//			e.printStackTrace();
        } finally {
            conn.disconnect();
        }
        return null;
    }

    // 通过输入流获得字节数组
    public static byte[] readStream(InputStream is) throws Exception {
        byte[] buffer = new byte[1024];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        is.close();
        return bos.toByteArray();
    }

    /**
     * 获取网址内容
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String getContent(String url) throws Exception {
        StringBuilder sb = new StringBuilder();

        HttpClient client = new DefaultHttpClient();
        HttpParams httpParams = client.getParams();
        // 设置网络超时参数
        HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
        HttpConnectionParams.setSoTimeout(httpParams, 5000);
        HttpResponse response = client.execute(new HttpGet(url));
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8192);

            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            reader.close();
        }
        return sb.toString();
    }

    /**
     * 检查代理，是否cnwap接入
     */
    private static void detectProxy() {
        ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo ni = cm.getActiveNetworkInfo();
        if (ni != null && ni.isAvailable() && ni.getType() == ConnectivityManager.TYPE_MOBILE) {
            String proxyHost = android.net.Proxy.getDefaultHost();
            int port = android.net.Proxy.getDefaultPort();
            if (proxyHost != null) {
                final InetSocketAddress sa = new InetSocketAddress(proxyHost, port);
                mProxy = new Proxy(Proxy.Type.HTTP, sa);
            }
        }
    }
}
